package com.joinway.framework.support.logging.service.impl;

import java.net.InetAddress;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.jdbc.datasource.DataSourceUtils;

import com.joinway.framework.core.utils.AppEnv;
import com.joinway.framework.core.utils.FrameworkHelper;
import com.joinway.framework.support.audit.constant.AuditConstants;
import com.joinway.framework.support.logging.service.ILogService;

public abstract class AbstractLogService implements ILogService {

	private final static Logger log = LoggerFactory.getLogger(AbstractLogService.class);
	
	private final static String DEFAULT_FLOW_ID = "X";
	
	protected DataSource dataSource;
	
	/**
	 * 代表当前节点环境变量的名称
	 */
	protected String nodeEnvVarName;
	
	protected String appIdEnvVarName;
	
	protected String appVersionEnvVarName;

	protected String[] remoteIpAttrNames;
	
	public abstract String getTable();
	
	@Override
	public void save(Map<String, Object> row){
		try{
			if(StringUtils.isBlank(getTable())){
				return;
			}
			
			if(row == null || row.size() == 0){
				return;
			}

			fulfillRow(row);
			
			Connection con = DataSourceUtils.getConnection(dataSource);
			
			String sql = StringUtils.join("insert into ", getTable(), "(" + StringUtils.join(row.keySet().iterator(), ",")
					, ") values (" , StringUtils.repeat(",?", row.size()).substring(1), ")");
			PreparedStatement stmt = con.prepareStatement(sql);
			
			int index = 1;
			Set<Entry<String, Object>> entries = row.entrySet();
			for(Entry<String, Object> entry : entries){
				Object value = entry.getValue();
				
				stmt.setObject(index, value);
				
				index++;
			}
			
			stmt.executeUpdate();
			stmt.close();
			
		}catch(Exception e){
			log.error("failed to save " + getTable(), e);
		}
	}
	
	protected void fulfillRow(Map<String, Object> row){
		if(row.get("flow_id") == null || StringUtils.isBlank(String.valueOf(row.get("flow_id")))){
			String flowId = MDC.get(AuditConstants.FLOW_KEY);
			if(StringUtils.isBlank(flowId)){
				flowId = DEFAULT_FLOW_ID;
			}
			row.put("flow_id", flowId);
		}
		
		String node = StringUtils.isBlank(nodeEnvVarName) ? AppEnv.getNode() : System.getProperty(StringUtils.trimToEmpty(nodeEnvVarName), AppEnv.getNode());
		if(StringUtils.isNotBlank(node)){
			row.put("node", node);
		}
		
		String appId = StringUtils.isBlank(appIdEnvVarName) ? AppEnv.getAppId() : System.getProperty(StringUtils.trimToEmpty(appIdEnvVarName), AppEnv.getAppId());
		if(StringUtils.isNotBlank(appId)){
			row.put("app_id", appId);
		}
		
		String version = StringUtils.isBlank(appVersionEnvVarName) ? AppEnv.getVersion() : System.getProperty(StringUtils.trimToEmpty(appVersionEnvVarName), AppEnv.getVersion());
		if(StringUtils.isNotBlank(version)){
			row.put("app_version", version);
		}
		
		String ip = null;
		HttpServletRequest request = FrameworkHelper.getHttpServletRequest();
		if(request != null){
			if(ArrayUtils.isNotEmpty(remoteIpAttrNames)){
				for(String name : remoteIpAttrNames){
					ip = (String)request.getAttribute(name);
					if(StringUtils.isNotBlank(ip)){
						break;
					}
				}
			}else{
				ip = request.getRemoteAddr();
			}
			
			row.put("http_method", request.getMethod());
			
			row.put("session_id", request.getSession().getId());
		}else{
			ip = "127.0.0.1";
		}
		
		HttpServletResponse response = FrameworkHelper.getHttpServletResponse();
		if(response != null){
			row.put("http_status_code", response.getStatus());
		}
		
		if(StringUtils.isNotBlank(ip)){
			row.put("remote_ip", ip);
		}
		
		try{
			String hostname = InetAddress.getLocalHost().getHostName();
			row.put("host_name", hostname);
		}catch(Exception e){
			log.error("failed to get hostname " + e.getMessage());
		}
		
		row.put("status", StringUtils.isBlank(String.valueOf(row.get("error_trace"))) ? 0 : 1);
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public String getNodeEnvVarName() {
		return nodeEnvVarName;
	}

	public void setNodeEnvVarName(String nodeEnvVarName) {
		this.nodeEnvVarName = nodeEnvVarName;
	}

	public String getAppIdEnvVarName() {
		return appIdEnvVarName;
	}

	public void setAppIdEnvVarName(String appIdEnvVarName) {
		this.appIdEnvVarName = appIdEnvVarName;
	}

	public String getAppVersionEnvVarName() {
		return appVersionEnvVarName;
	}

	public void setAppVersionEnvVarName(String appVersionEnvVarName) {
		this.appVersionEnvVarName = appVersionEnvVarName;
	}

	public String[] getRemoteIpAttrNames() {
		return remoteIpAttrNames;
	}

	public void setRemoteIpAttrNames(String[] remoteIpAttrNames) {
		this.remoteIpAttrNames = remoteIpAttrNames;
	}
}

